import { create } from 'zustand';
import { login as apiLogin, getUserInfo } from '@/api/user';

const useUserStore = create((set) => ({
  userInfo: null,
  isLogin: false,
  loading: false,
  error: null,

  // 登录
  login: async (username, password) => {
    set({ loading: true, error: null });
    try {
      const res = await apiLogin(username, password);
      const { token, data } = res.data;
      // 保存token和用户信息到本地存储
      localStorage.setItem('token', token);
      localStorage.setItem('userInfo', JSON.stringify(data));
      // 更新状态
      set({ userInfo: data, isLogin: true, loading: false });
      return true;
    } catch (error) {
      set({ error: error.message || '登录失败', loading: false });
      return false;
    }
  },

  // 登出
  logout: () => {
    set({ userInfo: null, isLogin: false });
    // 清除本地存储的用户信息和token
    localStorage.removeItem('userInfo');
    localStorage.removeItem('token');
  },

  // 初始化用户信息
  initUserInfo: async () => {
    const token = localStorage.getItem('token');
    const userInfo = localStorage.getItem('userInfo');
    
    if (!token || !userInfo) return;

    try {
      // 验证token是否有效
      await getUserInfo();
      set({ userInfo: JSON.parse(userInfo), isLogin: true });
    } catch (error) {
      // token无效，清除本地存储
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      set({ userInfo: null, isLogin: false });
    }
  }
}));

export default useUserStore;